import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'

import { useState, useEffect, useRef, useLayoutEffect } from 'react'

import { http } from '@/utils'

import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import './index.scss'

const { Option } = Select

const Publish = () => {
  // 要动态设置Form表单数据, 需要给Form组建的form属性指定这个form值
  const [form] = Form.useForm()

  // 路由
  const navigate = useNavigate()
  const [messageApi] = message.useMessage()
  const messageGenerate = (type, content) => {
    messageApi.open({
      type,
      content
    })
  }

  // 拿到路由中的id参数
  const [params] = useSearchParams()
  const articleId = params.get('id')
  const publishType = () => {
    return articleId ? '修改文章' : '发布文章'
  }

  // 频道列表
  const [channels, setChannels] = useState([])
  useEffect(() => {
    // 获取频道数据
    async function fetchChannels () {
      const res = await http.get('/channels')
      setChannels(res.data.channels)
    }
    fetchChannels()

    // 获取编辑的文章数据
    async function getArticle () {
      const res = await http.get(`/mp/articles/${articleId}`)
      const { cover, ...formValue } = res.data
      // 动态设置表单数据
      form.setFieldsValue({ ...formValue, type: cover.type })
      // console.log(formValue)

      //  封面图片回显
      // 格式化封面图片数据
      const imageList = cover.images.map(url => ({ url }))
      setFileList(imageList)
      setImgCount(cover.type)
      fileListRef.current = imageList
    }
    if (articleId) {
      // 拉取数据回显
      getArticle()
    }
  }, [])

  useLayoutEffect(() => {

  }, [messageApi])

  // 上传成功回调
  // 1. 声明一个暂存仓库
  const fileListRef = useRef([])
  const [fileList, setFileList] = useState([])
  const onUploadChange = info => {

    const fileList = info.fileList.map(file => {
      if (file.response) {
        return {
          url: file.response.data.url
        }
      }
      return file
    })

    // 2. 上传图片时，将所有图片存储到 ref 中
    fileListRef.current = fileList
    setFileList(fileList)
  }

  // 切换图片数量
  const [imgCount, setImgCount] = useState(1)
  const changeType = e => {
    // 使用原始数据作为判断条件
    const count = e.target.value
    setImgCount(count)

    if (count === 1) {
      // 单图，只展示第一张
      const firstImg = fileListRef.current[0]
      setFileList(!firstImg ? [] : [firstImg])
    } else if (count === 3) {
      // 三图，展示所有图片
      setFileList(fileListRef.current)
    }
  }

  // 发布文章
  const onFinish = async (values) => {
    console.log(values)
    // 数据的二次处理 重点是处理cover字段
    const { channel_id, content, title, type } = values
    const params = {
      channel_id,
      content,
      title,
      type,
      cover: {
        type: type,
        images: fileList.map(item => item.url)
      }
    }

    if (articleId) {
      // 编辑
      const res = await http.put(`/mp/articles/${articleId}?draft=false`, params)

      if (res.message === 'OK') {
        messageGenerate('success', '修改成功')
        setTimeout(() => {
          navigate("/article")
        }, 1000)
      } else {
        messageGenerate('error', '修改失败')
      }
    } else {
      // 新增
      const res = await http.post('/mp/articles?draft=false', params)

      if (res.message === 'OK') {
        messageGenerate('success', '发布成功')
        setTimeout(() => {
          navigate("/article")
        }, 1000)
      } else {
        messageGenerate('error', '修改失败')
      }
    }
  }


  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{publishType()}</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form onFinish={onFinish} form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          // 注意：此处需要为富文本编辑表示的 content 文章内容设置默认值
          initialValues={{ type: 1, content: '' }}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channels.map(item => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={changeType}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            {imgCount > 0 && (<Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList
              action="http://geek.itheima.net/v1_0/upload"
              fileList={fileList}
              onChange={onUploadChange}
              maxCount={imgCount}
              multiple={imgCount > 1}
            >
              <div style={{ marginTop: 8 }}>
                <PlusOutlined />
              </div>
            </Upload>)}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}
          >
            <ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {publishType()}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish